package com.wy.pdf_test;

import com.microsoft.playwright.*;
import com.microsoft.playwright.options.LoadState;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;

public class HtmlToPdfPlaywright {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions()
                    .setHeadless(true));
            Page page = browser.newPage();

            ClassPathResource htmlResource = new ClassPathResource("templates/examReport.html");
            // 加载 HTML 文件或 HTML 字符串
//            page.navigate("file:///D:/projects/code/study/sketch-study/examReport.html");
            File htmlFile = htmlResource.getFile(); // 获取本地 File 对象
            String fileUrl = htmlFile.toURI().toString(); // 转为 file:/// 协议格式的 URL
            page.navigate(fileUrl);

            // 等待 JS 执行完毕（确保图表渲染完成）
            page.waitForLoadState(LoadState.NETWORKIDLE);
            page.waitForTimeout(2000); // 可根据情况调整等待时间

            // 生成 PDF
            page.pdf(new Page.PdfOptions()
                    .setPath(Paths.get("output2.pdf"))
                    .setFormat("A4")
                    .setPrintBackground(true));

            System.out.println("✅ PDF 生成成功！");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
